clear
%% Problem parameters
%   'EqualMinima','Himmelblau','Sixhump','ModifiedRastrigin','Vincent',
%   'Shubert','Composition','IncreasingMinima','Rastrigin','Schaffer'.
ProblemSet.FuncType = 'Schaffer';
ProblemSet.dimension = 2;
% ProblemSet.k = [2,2,2,2,2];
% ProblemSet.BaseFunc = 3;

[d, x_bound, ObjFunc, OptSet, precision_init, precision, ~, MaximalBudget, FileName]...
    = problem_setting(ProblemSet);

MaximalBudget = 15000;
rep = 1;
iepsilon = 4;
epsilon = [0.1,0.01,0.001,0.0001];
NewRegionNum = 2;
MaxPartitionDepth_d = ceil(log((x_bound(2,:)-x_bound(1,:))./precision_init)...
    ./log(NewRegionNum));
MaxPartitionDepth = sum(MaxPartitionDepth_d)
ClearRadius0 = (x_bound(2,:)-x_bound(1,:))./(NewRegionNum.^(MaxPartitionDepth_d));
% ClearRadius = 2*sqrt(sum(ClearRadius0.^2)); % the maximum distance within a non-partitionable region
ClearRadius = 2*min(ClearRadius0);

Problem.Dimension = d;
Problem.Domain = reshape(x_bound,[1,d*2]);
Problem.Partition = @(Region,SampleSet)Partition_BoxConstraint(Region, NewRegionNum, MaxPartitionDepth, SampleSet);
Problem.Sampling = @(n, region)Sampling_BoxConstraint(n, region, ObjFunc);

%% optimization
% Algorithm parameters
AlgorithmM.n0 = 4;
AlgorithmM.QuantileLevel = 0.3;
AlgorithmM.NewBudget = 3;
AlgorithmM.MaxSampleSize = 10; %5*(d+1);
AlgorithmM.radius = ClearRadius;
AlgorithmM.local_search = @(starts,step)LocalSearch_BoxConstraint(ObjFunc,x_bound,starts,step,precision(iepsilon)./2,MaximalBudget);
AlgorithmM.StopCriteria = [1,MaximalBudget];
% AlgorithmM.StopCriteria = [2,size(OptSet.sol,1)];
% AlgorithmM.StopCriteria = [3,5000];

%% STAGE ONE PRS-MMO
time_start = tic;
for i=1:rep
[optima, RegionSet, SampleSet, RegionSampleId, TotalBudget_Stage2] = prsmmo_ls( Problem, AlgorithmM );
end
toc(time_start)
TotalBudget = size(SampleSet,1)
TotalBudget_Stage2

%% save data
save(FileName)

%% Figure
figure()
hold on
rectangle('Position',[Problem.Domain([1,3]),Problem.Domain([2,4])-Problem.Domain([1,3])])
for i=1:length(RegionSet)
    if RegionSet(i,2) == 0
        rectangle('Position',[RegionSet(i,[3,5]),RegionSet(i,[4,6])-RegionSet(i,[3,5])])
    end
end
hold off
